package com.bjpowernode.controller;

import com.bjpowernode.pojo.ProductInfo;
import com.bjpowernode.pojo.vo.ProductInfoVo;
import com.bjpowernode.service.ProductInfoService;
import com.bjpowernode.utils.FileNameUtil;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/prod")
public class ProductInfoAction {
    //每页显示的记录数
    public static final int PAGE_SIZE =5;
    //异步上传图片名称
    String saveFileName ="";

    //切记要业务逻辑层对象
    @Autowired
    ProductInfoService productInfoService;
    //显示全部商品不分页
    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request){
        List<ProductInfo> list = productInfoService.getAll();
        request.setAttribute("list",list);
        return "product";
    }
    //显示第一页商品
    @RequestMapping("/split")
    public String split(HttpServletRequest request){
        PageInfo info =null;
        Object vo = request.getSession().getAttribute("prodVo");
        if (vo!=null){
            info = productInfoService.splitPageVo((ProductInfoVo)vo,PAGE_SIZE);
            request.getSession().removeAttribute("prodVo");
        }else {
            //得到第一页数据
            info = productInfoService.splitPage(1,PAGE_SIZE);

        }
        request.setAttribute("info",info);
        return "product";
    }

    //ajax分页处理
    //该注解用于将 Controller 的方法返回的对象，通过 HttpMessageConverter 接口转换为指定格式的
    //数据如：json,xml 等，通过 Response 响应给客户端
    //RespondBody注解是会把返回值当做响应体响应到浏览器中
    @ResponseBody
    @RequestMapping("/ajaxSplit")
    public void ajaxSplit(ProductInfoVo vo, HttpSession session){
        PageInfo info = productInfoService.splitPageVo(vo,PAGE_SIZE);
        session.setAttribute("info",info);
        //session优先级更高所以request中的被覆盖
    }

    //多条件查询功能
    //ResponseBody解析ajax请求
    @ResponseBody
    @RequestMapping("/condition")
    public void condition(ProductInfoVo vo,HttpSession session){
        List<ProductInfo> list = productInfoService.selectCondition(vo);
        session.setAttribute("list",list);
    }

    //异步ajax图片上传@ResponseBody要这个回传
    //MultipartFile专门处理文件上传
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage,HttpServletRequest request){
        //提取生成文件名UUID+上传图片的后缀.jpg
         saveFileName = FileNameUtil.getUUIDFileName()+FileNameUtil.getFileType(pimage.getOriginalFilename());
        //得到项目组图片存储路径
        String path = request.getServletContext().getRealPath("/image_big");
        //转存 path = 当前工作路径+File.separator（反斜杠）\***.jpg
        try {
            pimage.transferTo(new File(path+File.separator+saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回客户端JSON对象，封装图片路径，实现回显
        JSONObject object = new JSONObject();
        object.put("imgurl",saveFileName);
        //注意直接返回是object对象要json要转成string
        return object.toString();
    }

    @RequestMapping("/save")
    public String save(ProductInfo info,HttpServletRequest request){
        info.setpImage(saveFileName);
        info.setpDate(new Date());
        int num=-1;
        try {
            num =productInfoService.save(info);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (num>0){
            request.setAttribute("msg","增加成功");
        }else {
            request.setAttribute("msg","增加失败");
        }
        //清空saveFileName为下次新增或修改的ajax上传处理
        saveFileName="";

        //成功后重新访问数据库，跳转分页显示action
        return "forward:/prod/split.action";
    }

    @RequestMapping("/one")
    public String one(int pid,ProductInfoVo vo, Model model,HttpSession session){
        ProductInfo info = productInfoService.getByID(pid);
        model.addAttribute("prod",info);
        //将多条件及页码放入session
        session.setAttribute("prodVo",vo);
        return "update";
    }

    @RequestMapping("/update")
    public String update(ProductInfo info,HttpServletRequest request){
        //因为ajax的异步图片上传，如果有上传的则有图片名称，没有则其为空使用隐藏表单提供的原始图片名
        if (!saveFileName.equals("")){
            info.setpImage(saveFileName);
        }
        //完成更新
        int num =-1;
        try {
            num = productInfoService.update(info);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (num >0) {
            //成功
            request.setAttribute("msg","更新成功");
        } else {
            //失败
            request.setAttribute("msg","更新失败");
        }
        //清空saveFilname为下次做准备
        saveFileName="";
        return "forward:/prod/split.action";
    }

    @RequestMapping("delete")
    public  String delete(int pid,ProductInfoVo vo,HttpServletRequest request){
        int num =-1;
        try {
            num= productInfoService.delete(pid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num >0) {
            //成功
            request.setAttribute("msg","删除成功");
            request.getSession().setAttribute("deleteProdVo",vo);
        } else {
            //失败
            request.setAttribute("msg","删除失败");
        }
        //删除成功后跳转分页显示
        return "forward:/prod/deleteAjaxSplit.action";
    }
    @ResponseBody
    @RequestMapping(value = "/deleteAjaxSplit",produces = "text/html;charset=UTF-8")
    public Object deleteAjaxSplit(HttpServletRequest request){

        PageInfo info =null;
        Object vo = request.getSession().getAttribute("deleteProdVo");
        if (vo!=null){
            info = productInfoService.splitPageVo((ProductInfoVo) vo,PAGE_SIZE);
        }else {
            info = productInfoService.splitPage(1,PAGE_SIZE);

        }
        //得到第一页数据
        request.getSession().setAttribute("info",info);
        return request.getAttribute("msg");
    }
    //批量删除商品
    @RequestMapping("/deleteBatch")
    private String deleteBatch(String pids,HttpServletRequest request){
        //将上传的字符串搞成数组
        String []ps = pids.split(",");
        try {
        int num = productInfoService.deleteBatch(ps);
    

            if (num >0) {
                //成功
                request.setAttribute("msg","批量删除成功");
            } else {
                //失败
                request.setAttribute("msg","批量删除失败");
            }
        } catch (Exception e) {
            request.setAttribute("msg","商品不可删除");

        }

        return "forward:/prod/deleteAjaxSplit.action";
    }


}
